package com.webserver.controller;

import com.webserver.entity.Article;
import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;

import java.io.*;

public class ArticleController {
    private static File articleDir;
    static {
        articleDir = new File("./articles");
        if (!articleDir.exists()){
            articleDir.mkdirs();
        }
    }


    public void submitarticle(HttpServletRequest request, HttpServletResponse response){
        String title = request.getParameter("title");
        String content = request.getParameter("content");
        String author = request.getParameter("author");
        if (title.isEmpty() || content.isEmpty() || author.isEmpty()){
            response.sendRedirect("/myweb/article_fail.html");
            return;
        }else {
            Article article = new Article(title, author, content);
            File articleFile = new File(articleDir, title + ".obj");
            if (articleFile.exists()){
                response.sendRedirect("/myweb/article_fail.html");
                return;
            }
            try(
                    ObjectOutputStream objectOutputStream =
                            new ObjectOutputStream(new FileOutputStream(articleFile))
                    ) {
                objectOutputStream.writeObject(article);
                response.sendRedirect("/myweb/article_success.html");
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
